package com.zhdl.websocket.service.impl;

import com.zhdl.websocket.service.WebSocketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
public class WebSocketServiceImpl implements WebSocketService {

    public Map<String, Session> sessionMap = new ConcurrentHashMap<>();

    /**
     * 保存 sessionMap 集合
     *
     * @param sid
     * @param session
     */
    @Override
    public void saveSessionMap(String sid, Session session) {
        sessionMap.put(sid, session);
    }

    /**
     * 删除 sessionMap 集合
     *
     * @param sid
     */
    @Override
    public void deleteSessionMap(String sid) {
        sessionMap.remove(sid);
    }

    /**
     * 推送客户端消息
     *
     * @param sid
     * @param msg
     */
    @Override
    public void pushCustomMsg(String sid, String msg) {

        Session session = sessionMap.get(sid);

        if (session != null && session.isOpen()) {
            session.getAsyncRemote().sendText(msg);
        } else {
            log.error("客户端 {} sessionId 已关闭", sid);
        }
    }

    /**
     * 实现服务器主动推送 - 与上个方法 差别不大
     *
     * @param message
     */
    @Override
    public void sendMessage(String message) {
        /*
            通过Map.keySet遍历key和value
         */
        for (String key : sessionMap.keySet()) {
            System.out.println("key= " + key + " and value= " + sessionMap.get(key));
            try {
                sessionMap.get(key).getBasicRemote().sendText(message);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }


}
